import merge from 'lodash/merge';
import { initServer, registerServerPlugins } from '@kuiper/cli/server.js';
import { NEW_USER } from '@kuiper/auth';
import readConfig from '@kuiper/cli/readConfig.js';

import pkg from '../../package.json';

import { plugin } from './index';
import defaultConfig from '../config';

const DEV =
	process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test';
export default async function initServerInstance({ loggerConfig }) {
	process.env.NO_INIT_QUEUE_WORKER = 1;

	const server = await initServer({});

	const { config, browserConfig, serverPlugins, browserPlugins } = readConfig();
	if (
		process.env.NODE_ENV === 'development' ||
		process.env.NODE_ENV === 'test'
	) {
		config[pkg.name] = merge(defaultConfig, config[pkg.name]);
	}

	Object.assign(server.app, {
		config,
		browserConfig,
		serverPlugins,
		browserPlugins,
	});
	if (loggerConfig) {
		server.app.config['@kuiper/react-base'].logger = loggerConfig;
	}

	await registerServerPlugins({
		server,
		plugins: DEV ? config.plugins.filter(x => x !== pkg.name) : config.plugins,
	});

	server.events.removeAllListeners(NEW_USER);

	if (DEV) {
		await server.register({
			plugin,
			options: config[pkg.name],
		});
	}

	return server;
}
